Jest는 Facebook에서 만든 JavaScript 테스트 프레임워크로, 주로 React 환경에서 많이 사용되지만 Node.js, TypeScript 등 다양한 프로젝트에서도 활용 가능합니다.
# 프로젝트 로컬 설치
npm install --save-dev jest
npm install --save-dev ts-jest @types/jest
npx ts-jest config:init
npx jest
package.json
에 script 등록 시{
"scripts": {
"test": "jest"
}
}
npm test
__tests__
폴더, 또는 *.test.js
, *.spec.js
파일을 자동 인식합니다.describe
: 테스트 그룹화test
/ it
: 개별 테스트 케이스 작성expect
: 결과 검증 (Matcher와 함께 사용)// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
// sum.test.js
const sum = require("./sum");
describe("sum 함수", () => {
test("1 + 2는 3이다", () => {
expect(sum(1, 2)).toBe(3);
});
it("10 + 20은 30이다", () => {
expect(sum(10, 20)).toBe(30);
});
});
Jest는 다양한 Matcher를 제공하여 직관적인 검증이 가능합니다.
expect(2 + 2).toBe(4); // 원시값 비교
expect({ a: 1 }).toEqual({ a: 1 }); // 객체/배열 구조 비교
expect(true).toBeTruthy();
expect(0).toBeFalsy();
expect([1, 2, 3]).toContain(2);
expect("Hello Jest").toMatch(/Jest/);
function throwError() {
throw new Error("Oops!");
}
expect(() => throwError()).toThrow("Oops!");
Jest는 Promise, async/await, 콜백 기반 비동기 코드도 지원합니다.
// async.js
function fetchData() {
return Promise.resolve("data");
}
module.exports = fetchData;
// async.test.js
const fetchData = require("./async");
test("비동기 데이터 반환", async () => {
const data = await fetchData();
expect(data).toBe("data");
});
테스트 실행 전후에 공통 로직을 설정할 수 있습니다.
beforeAll(() => {
// 전체 테스트 시작 전에 1회 실행
});
afterAll(() => {
// 전체 테스트 종료 후 1회 실행
});
beforeEach(() => {
// 각 테스트 시작 전에 실행
});
afterEach(() => {
// 각 테스트 종료 후 실행
});
테스트에서 외부 의존성을 제거하고 동작을 시뮬레이션할 수 있습니다.
const myFn = jest.fn().mockReturnValue(42);
test("jest.fn 예제", () => {
expect(myFn()).toBe(42);
expect(myFn).toHaveBeenCalled();
});
// api.js
exports.getUser = () => ({ id: 1, name: "Alice" });
// api.test.js
jest.mock("./api");
const api = require("./api");
test("모듈 모킹", () => {
api.getUser.mockReturnValue({ id: 99, name: "Mocked" });
expect(api.getUser()).toEqual({ id: 99, name: "Mocked" });
});
프론트엔드에서 많이 쓰이는 setTimeout, setInterval을 제어할 수 있습니다.
jest.useFakeTimers();
test("타이머 제어", () => {
const callback = jest.fn();
setTimeout(callback, 1000);
jest.advanceTimersByTime(1000); // 1초 경과 시뮬레이션
expect(callback).toHaveBeenCalled();
});
UI 변경을 감지할 수 있습니다.
import renderer from "react-test-renderer";
import Button from "./Button";
test("Button snapshot", () => {
const tree = renderer.create(<Button label="Click" />).toJSON();
expect(tree).toMatchSnapshot();
});
🔟 Jest 실행 옵션 (CLI)
--watch
: 파일 변경 시 자동 재실행--coverage
: 테스트 커버리지 리포트--runInBand
: 병렬 대신 순차 실행 (디버깅 시 유용)npx jest --watch
npx jest --coverage
npx jest --runInBand